package nl.saxion.ami;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

public class SensorwaardeDAO {


	public static Sensor getLaatsteWaarde(int sensorid){

		Connection c = DBConnection.getInstance().getConnection();
		Statement stmt = null;
		Sensor sensor = null;
		try {
			stmt = c.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT waarnemingen.waarde, sensoren.naam FROM waarnemingen INNER JOIN sensoren ON waarnemingen.sensorid=sensoren.sensorid WHERE waarnemingen.sensorid=" + sensorid + " ORDER BY tijd DESC LIMIT 1");
			while (rs.next()){
				sensor = new Sensor();
				sensor.setId(sensorid);
				sensor.setNaam(rs.getString("naam"));
				sensor.setWaarde(rs.getDouble("waarde"));
			}
			//close connection
			//                      c.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return sensor;
	}


	public static WaardenReeksLijst getWaardeReeks(int sensorid){
		Connection c = DBConnection.getInstance().getConnection();
		Statement stmt = null;
		HashMap<Long, Double> reeks = new HashMap<Long, Double>();
		WaardenReeksLijst retVal = new WaardenReeksLijst();

		try {
			stmt = c.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT * FROM waarnemingen WHERE sensorid=" + sensorid + " ORDER BY tijd DESC LIMIT 100");
			while (rs.next()){
				long l = rs.getTimestamp("tijd").getTime();
				reeks.put(l, rs.getDouble("waarde"));
			}
			//close connection
			//                  c.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		retVal.setWaarden(reeks);
		return retVal;
	}

}